package com.workflow.engine.eb.steps.jd.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.workflow.engine.core.flow.StepState;
import com.workflow.engine.parser.annotation.PGConfig;
import com.workflow.engine.parser.annotation.PGScheme;
import com.workflow.engine.parser.constant.HttpMethod;
import com.workflow.engine.parser.flow.impl.AbstractStep;
import com.workflow.engine.parser.strategy.StrategyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import static com.workflow.engine.eb.util.BizMethodUtil.jsonEncode;
import static com.workflow.engine.parser.utils.StepStateUtil.successfulStepState;

/**
 * https://passport.jd.com/uc/showAuthCode?r=0.8793774094964901&version=2015
 * 是否需要显示验证码校验
 *
 * Created by Administrator on 2017/6/8.
 */
@PGConfig({
        @PGScheme(requestParamName = "r", strategy = StrategyType.FIXED, strategyNeedParams = "0.8793774094964901"),
        @PGScheme(requestParamName = "version", strategy = StrategyType.FIXED, strategyNeedParams = "2015"),
})
public class JDShowAuthCodeVerify extends AbstractStep {

    private static final Logger logger = LoggerFactory.getLogger(JDShowAuthCodeVerify.class);

    @Override
    public Logger getLogger() {
        return logger;
    }

    @Override
    protected String getRequestUrl() {
        return "https://passport.jd.com/uc/showAuthCode";
    }

    @Override
    protected HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

    @Override
    protected Map<String, String> getHeaders() {
        return new HashMap<String, String>(){{
            put("Host", "passport.jd.com");
            put("Connection", "keep-alive");
            put("Accept", "text/plain, */*; q=0.01");
            put("Origin", "https://passport.jd.com");
            put("X-Requested-With", "XMLHttpRequest");
            put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36");
            put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            put("Referer", "https://passport.jd.com/new/login.aspx");
            put("Accept-Encoding", "gzip, deflate, br");
            put("Accept-Language", "zh-CN,zh;q=0.8");
        }};
    }

    @Override
    protected StepState handleResponse(Map<String, Object> context, Object response) throws Exception {
        JSONObject result = JSON.parseObject(jsonEncode(response.toString().replaceAll("\\(|\\)", "")));
        logger.info("result is {}", result);
//        if((Boolean)result.get("verifycode")){
            if ((Boolean)result.get("verifycode")) {
                return successfulStepState(this, "需要");
            } else {
                return successfulStepState(this, "不需要");
            }
//        } else {
//            logger.error("未知异常：{}", result);
//            return failureStepState(this);
//        }
    }
}
